#断言工具封装
import json
import os
import logging
import pymysql
from bs4 import BeautifulSoup
from jinja2.async_utils import auto_aiter
from config import DIR_PARTH
from logging.handlers import TimedRotatingFileHandler

def common_assert(repose,status_code=None,json_desc=None,text=None):
    #如果status_code不为空则断言
    if status_code :
        assert repose.status_code == status_code , "状态码断言错误，预期状态码{}!=实际状态码{}".format(status_code,repose.status_code)
    if json_desc :
        assert json_desc in repose.json().get('description'),"json断言错误，预期结果{}不包含在实际结果{}".format(json_desc,repose.json().get('description'))
    if text :
        assert text in repose.text,"text断言错误，预期结果{}！=实际结果{}".format(text,repose.text)
#读取数据json工具
#传接口名获取数据
def read_json (filename ,key):
    arrs=[]
    #文件路径
    filepath=DIR_PARTH+os.sep+"data"+os.sep+filename
    with open(filepath,"r",encoding="utf-8") as f:
        #循坏读取key的值
       for data in json.load(f).get(key):
           #进行剪切，要desc后面的数据并强转为元组类型
           arrs.append(tuple(data.values())[1:])
    return arrs
#日志工具
class GetLog:
    log = None
    @classmethod
    def get_log(cls):
        if cls.log is None:
            #获取日志器
            cls.log = logging.getLogger()
            #设置入口级别
            cls.log.setLevel(logging.INFO)
            #设置文件，通过时间切割文件大小
            filepath=DIR_PARTH+os.sep+"log"+os.sep+"p2p.log"
            tf = logging.handlers.TimedRotatingFileHandler(filename=filepath,
                                                           when='D'
                                                           ,interval=1
                                                           ,backupCount=3
                                                           ,encoding='utf-8')
            #设置格式
            fm="%(asctime)s %(levelname)s %(name)s %(filename)s %(message)s"

            fmt = logging.Formatter(fm)
            # 将格式添加到文件中
            tf.setFormatter(fmt)
            #将文件添加到日志文件中
            cls.log.addHandler(tf)
        return cls.log
#提取html工具
def html_parse(result):
    data = {}
    #获取html对象
    html = result.json().get('description').get('form')
    #创建bs4实例
    bs = BeautifulSoup(html,"html.parser")
    #提取url
    url = bs.form.get('action')
    print("获取的url是",url)
    data["url"] = url
    #提取所有的input标签，要提取name 和value
    for  i in bs.find_all('input'):
        data[i.get("name")] =i.get("value")
    return url, data
#数据库工具封装
def connect_mysql(sql):
    connect =None
    cursor = None
    try:
        #连接数据库
        connect = pymysql.connect(host="121.43.169.97",
                                  user="student",
                                  password="P2P_student_2023",
                                  database="czbk_member",
                                  port=3306,
                                  charset='utf8' ,
                                  autocommit=True,)# 自动提交，手动控制事务需要关闭
        #创建游标
        cursor = connect.cursor()
        #执行sql语句
        cursor.execute(sql)
        if sql.lower().split()[0] == "select":
            #查询语句返回所有
             return cursor.fetchall()
        else:
            #返回影响的行数
            return cursor.rowcount
    except Exception as e:
        print("sql出错了",e)
        connect.rollback()
        #关闭游标
    finally:
        if cursor:
            cursor.close()
        #关闭连接
        if connect:
            connect.close()
#清除数据
def clear_data():
    sql_1 = """delete info.* from czbk_member.mb_member as mb  
    INNER JOIN czbk_member.mb_member_info as info  on 
    info.member_id=mb.id where mb.phone in
    ("13600001121","13600001131","13600001141","13600001151");
    """
    connect_mysql(sql_1)
    sql_2 = """
    delete login.* from czbk_member.mb_member as mb  INNER JOIN czbk_member.mb_member_login_log as login  on login.member_id=mb.id where mb.phone in("13600001121","13600001131","13600001141","13600001151");
    """
    connect_mysql(sql_2)
    sql_3 = """
    delete from czbk_member.mb_member  where phone in  ("13600001121","13600001131","13600001141","13600001151");
    """
    connect_mysql(sql_3)
    sql_4 = """
    delete from czbk_member.mb_member_register_log where phone in ("13600001121","13600001131","13600001141","13600001151");
    """

    connect_mysql(sql_4)

if  __name__=="__main__":
    print(read_json("register_login.json", key="login_status"))